<template>
  <el-form
    ref="userForm"
    :model="userInfo"
    :rules="rules"
    label-width="120px"
    style="margin-left: 120px; margin-top: 30px"
  >
    <el-form-item label="姓名:" prop="username">
      <el-input v-model="userInfo.username" style="width:300px" />
    </el-form-item>
    <el-form-item label="密码:" prop="password">
      <el-input v-model="userInfo.password" type="password" style="width:300px" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="doUpdate">更新</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import { getUserDetail, updateUserInfo } from '@/api/user'

export default {
  data() {
    return {
      userInfo: {
        username: '',
        password: ''
      },
      rules: {
        username: [{ required: true, message: '姓名不能为空', trigger: ['blur', 'change'] }],
        password: [{ required: true, message: '密码不能为空', trigger: ['blur', 'change'] }]
      }
    }
  },
  created() {
    this.loadUserDetail()
  },
  methods: {
    async loadUserDetail() {
      const res = await getUserDetail(this.$route.params.id)
      console.log(res)
      this.userInfo = res.data
    },
    // 更新用户信息
    async doUpdate() {
      try {
        await updateUserInfo({ ...this.userInfo, id: this.$route.params.id })
        this.$message.success('更新成功')
        this.loadUserDetail()
      } catch (error) {
        this.$message.error('更新失败')
        console.log(error)
      }
    }
  }
}
</script>
